<?php

namespace app\home\controller;

use think\Controller;
//引入公共控制器
use app\common\controller\Home;
//Business继承Home，Home继承Controller ，那么Business即有公共控制器(Home)的功能，也有底层控制器(Controller)的功能

//引入邮箱发送类
use app\common\library\Email;

//系统自带配置的模型
use app\common\model\Config as ConfigModel;

class Business extends Home
{
    public function __construct()
    {
        parent::__construct();

        $this->BusinessModel = model('Business.Business');
        $this->EMSModel = model('Ems');
        $this->RegionModel = model('Region');
        $this->OrderModel = model('Subject.Order');
        $this->CategoryModel = model('Subject.Category');
        $this->CommentModel = model('Subject.Comment');
        $this->CollectModel = model('Subject.Collect');
        $this->CollectionModel = model('Business.Collection');
        $this->RecordModel = model('Business.Record');
        $this->LikesModel = model('Business.Likes');
        $this->PayModel = model('Pay.Pay');
    }

    public function index()
    {   
        //默认是从...home/view开始
        return $this->view->fetch();
    }

    //基本资料
    public function profile()
    {   

        if($this->request->isPost())
        {   
            // $params = $this->request->param();

            //接收数据
            $nickname = $this->request->param('nickname','','trim');
            $mobile = $this->request->param('mobile','','trim');
            $email = $this->request->param('email','','trim');
            $password = $this->request->param('password','','trim');
            $gender = $this->request->param('gender','','trim');
            $region = $this->request->param('region','','trim');

            //组装数据
            $data = [
                'id' => $this->view->AutoLogin['id'], //传入了主键id，save()方法执行的才会是更新的sql操作
                'nickname'=> $nickname,
                'mobile'=> $mobile,
                'gender'=> $gender,
            ];

            //判断密码是否不为空
            //若密码为空，则代表不需要修改密码，若不为空，则需要给新密码添加上新的密码盐进行md5加密
            if(!empty($password))
            {
                //生成一个新的10位的密码盐
                $salt = randstr(10);

                //对新密码进行加密
                $repass  = md5($password. $salt);

                //追加新数据
                $data['password'] = $repass;
                $data['salt'] = $salt;
            }

             //判断邮箱是否为新邮箱,如果是新邮箱则需要重新验证
             if($email != $this->view->AutoLogin['email'])
             {
                $data['email'] = $email;
                $data['auth'] = '0';
             }

             //查询当前所在区域
             if($region)
             {
                $parent = $this->RegionModel->where(['code'=>$region])->value('parentpath');

                if($parent)
                {
                    $parent = explode(',', $parent);
                    
                    $province = isset($parent[0]) ? $parent[0] : null;
                    $city = isset($parent[1]) ? $parent[1] : null;
                    $district = isset($parent[2]) ? $parent[2] : null;

                    //追加数据
                    $data['province'] = $province;
                    $data['city'] = $city;
                    $data['district'] = $district;
                    
                }
             }


             //判断是否有文件上传
             if($_FILES['avatar']['error'] == 0 && $_FILES['avatar']['size'] > 0 )
             {      
                    //上传头像的方法
                    $success =  build_upload('avatar');
                    if($success['code'])
                    {
                        //上传成功
                        $data['avatar'] = $success['data'];
                    }else
                    {
                        //上传失败
                        $this -> error($success['msg']);
                        exit;
                    }
             }


             //save方法可用作新增插入语句或者更新语句
             //具体执行的是更新还是插入操作的区别在于数据中有没有传入对应元素的id值，即传入主键id
             //若传入了主键id，则会执行的是更新语句，否则执行新增插入的语句
             //save的方法是专门给模型使用的
             //更新数据库
             $result = $this->BusinessModel->validate('common/Business/Business')->isUpdate(true)->save($data);

             if($result === FALSE)
             {
                $this->error($this->BusinessModel->getError());
                exit;
             }else
             {  
                //若用户存在旧头像，此时又上传了新头像
                //则需要将旧头像进行删除
                //先判断是否有上传新头像
                if(isset($data['avatar']))
                {   
                    //判断文件是否存在，若存在则进行删除操作
                    //  /uploads/123123/123123.jpg, 再该文件路径前加一个. 变成./uploads/123123/123123.jpg
                    @is_file(".".$this->view->AutoLogin['avatar']) 
                    && 
                    @unlink(".".$this->view->AutoLogin['avatar']);  //unlink()方法用于删除文件
                }
                $this->success('更新个人资料成功',url('home/business/index'));
                exit;
             }

        }
    
        // 默认路径:view/business/profile.html
        return $this->view->fetch();

    }

    //邮箱认证    
    public function email()
    {   
        //邮箱认证
        //邮箱认证的步骤：点击发送按钮 ——> 发送Ajax请求 -> 
        //控制器接收 ——> 开启事务 -> 删除过期的验证码记录 -> 插入最新的验证码 ->
        //最后是发送验证码
        //拦截判断
        //判断是否有ajax请求
        if($this->request->isAjax())
        {
            //接收acion参数
            $action = $this->request->param('action','','trim');
            //若action为send，则代表要发送验证码
            if($action == 'send')
            {
                //获取接收方的邮箱
                $receive = $this->view->AutoLogin['email'];

                if($this->view->AutoLogin['auth'] == '1')   //auth等于1 说明已经验证了
                {
                    $this->error('您已通过邮箱认证，无需重复认证！');
                    exit;
                }

                //获取系统的配置，并实例化邮件对象
                // \think\Config::set('site',array_merge(\think\Config::get('site'),$row));
                $email = new Email;

                //生成随机字符串
                $code = randstr(5);
                $subject = "【FAST邮箱验证】";
                $message = "<h3>您的邮箱验证码为:$code</h3>";
                
                


                //删除掉邮箱内存有的旧的验证码,即每次发送新的验证码之前都会进行邮箱初始化操作
                //开启事务
                $this->EMSModel->startTrans();

                //执行删除语句
                $DeleteStatus = $this->EMSModel->where(['email' => $receive])->delete();

                if($DeleteStatus === FALSE)
                {
                    $this -> error('删除过期验证码失败');
                    exit;
                }

                //插入语句
                $data = [
                    'event' => 'auth', //自己命名的事件名称
                    'email' => $receive, //收件人
                    'code'  => $code,  //生成的随机字符串
                    'times' => 0,      //验证次数
                ];

                //插入语句
                $InsertStatus = $this->EMSModel->save($data);

                //插入失败
                if($InsertStatus === FALSE)
                {   
                    //回滚上一步的动作
                    $this->EMSModel->rollback();
                    $this->error('插入验证码失败');
                    exit;
                }

                //综合判断
                if($DeleteStatus === FALSE || $InsertStatus === FALSE)
                {
                    $this->EMSModel->rollback();
                    $this->error('存入验证码失败');
                    exit;
                }

                //发送验证码
                $result = $email->to($receive)
                            ->subject($subject)
                            ->message($message)
                            ->send();
                if($result)
                {   
                    //若两个状态都没有出错，则进行事务提交
                    $this->EMSModel->commit();

                    //发送邮件成功
                    $this->success('邮件已发送, 请注意查收');
                    exit;
                }else
                {
                    //如果邮件发送失败了，则需要将数据库回滚
                    $this->EMSModel->rollback();
                    $this->error("邮件发送失败:".$email->getError());
                    exit;
                }

            }
        }
        //用于接收表单的判断
        if($this->request->isPost())
        {
            $code = $this ->request -> param('code','','trim');
            $email = $this ->view ->AutoLogin['email'];

            //查看验证码是否正确
            $where = [
                'code' => $code,
                'email' => $email
            ];
            $check = $this->EMSModel->where($where)->find();
            

            if(!$check)
            {
                $this->error('验证码输入有误，请重新输入');
                exit;
            }
            
            //开启事务
            $this->EMSModel->startTrans();
            $this->BusinessModel->startTrans();

            //删除邮件记录表
            $EMStatus = $this->EMSModel ->where($where)->delete();

            //打印语句
            // echo $this ->EMSModel->getLastSql();
            // exit;
            
            if($EMStatus === FALSE)
            {
                $this -> error('验证码删除失败');
                exit;
            }

            //会员表的更新
            $data = [
                'id'   => $this->view->AutoLogin['id'], //给主键id是告诉save()方法需要执行的操作是更新而不是新增
                'auth' => '1',  //已认证通过
            ];

            //执行更新语句
            $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($data);

            //打印sql语句
            // echo $this->BusinessModel->getLastSql();
            // exit;

            if($BusinessStatus === FALSE)
            {
                //删除验证码失败，进行回滚
                //邮件回滚
                $this ->EMSModel->rollback();
                $this ->error($this->EMSModel->getError());
                exit;
            }
            
            //综合判断 
            if($EMStatus === FALSE || $BusinessStatus === FALSE)
            {
                $this->BusinessModel->rollback();
                $this->EMSModel->rollback();
                $this->error('验证状态更新失败');
                exit;
            }else//走进else即两个都是true
            {
                //提交事务
                $this->EMSModel->commit();
                $this->BusinessModel->commit();

                $this->success('邮箱认证成功',url('home/business/index'));
                exit;
            }


        }
        return $this->view->fetch();
    }

    //我的课程
    public function subject()
    {
        if($this->request->isAjax())
        {
            $page = $this->request->param('page',1,'trim');
            $limit = $this->request->param('limit',10,'trim');
            $keywords = $this->request->param('keywords','','trim');

            //偏移量
            $start = ($page-1)*$limit;

            $where = ['order.busid' => $this->view->AutoLogin['id']];

            //搜索栏关键词搜索
            if(!empty($keywords))
            {
                $where['title'] = ['LIKE',"%$keywords%"];
            }

            //查询数据总条数
            $count = $this ->OrderModel->with(['subject','comment'])->where($where)->count();

            //查询数据
            $list = $this->OrderModel
                         ->with(['subject','comment'])
                         ->where($where)
                         ->order('order.id','desc')
                         ->limit($start,$limit)
                         ->select();

            if($list)
            {
                foreach($list as $item)
                {
                    $cateid = isset($item['subject']['cateid']) ? trim($item['subject']['cateid']): 0;

                    $item['cate'] =  $this->CategoryModel->where(['id'=> $cateid])->value('name');
                }
            }

            $data = [
                'count' => $count,
                'list'  => $list
            ];

            if($list)
            {
                //成功返回
                $this->success('返回列表',null,$data);
                exit;
            }else
            {
                //失败返回
                $this->error('暂无数据',null,$data);
                exit;
            }
        }

        return $this->view->fetch();
    }

    //评价界面
    public function comment()
    {   
        $orderid = $this->request->param('orderid',0,'trim');

        $order = $this->OrderModel->with(['subject','comment'])->find($orderid);

        if(!$order)
        {
            $this->error('订单不存在');
            exit;
        }

        if($this->request->isPost())
        {
            $rate = $this->request->param('rate',5,'trim');
            $content = $this->request->param('content','','trim');

            $data = [
                'busid' => $this->view->AutoLogin['id'],
                'subid' => $order['subid'], 
                'rate'  => $rate,
                'content' => $content,
                'orderid' => $order['id']
            ]; 

            $result = $this->CommentModel->validate('common/Subject/Comment')->save($data);

            if($result === FALSE)
            {
                $this->error($this->CommentModel->getError());
                exit;
            }else
            {
                $this->success('评价成功',url('home/business/subject'));
                exit;
            }
        }

        //将数据传回前端
        $this->assign('order', $order);
       
        return $this->view->fetch();
    }

    //联系我们
    public function contact()
    {
        $this->assign([
            'mobile1' => config('site.mobile1'),
            'mobile2' => config('site.mobile2'),
            'mobile3' => config('site.mobile3'),
            'ContactBack' => config('site.ContactBack'),
        ]);
        return $this->view->fetch();
    }
    
    //我的收藏
    public function collect()
    {   
        if($this->request->isAjax())
        {   
            $page = $this->request->param('page',1,'trim');
            $limit = $this->request->param('limit',10,'trim');
            $keywords = $this->request->param('keywords','','trim');

            //偏移量
            $start = ($page-1)*$limit;

            $where = ['busid' => $this->view->AutoLogin['id']];

            //搜索栏关键词搜索
            if(!empty($keywords))
            {
                $where['title'] = ['LIKE',"%$keywords%"];
            }

            //查询数据总条数
            $count = $this ->CollectModel->with(['business'])->where($where)->count();

            //查询数据
            $list = $this->CollectModel
                         ->with(['business'])
                         ->where($where)
                         ->limit($start,$limit)
                         ->select();

            if($list)
            {
                foreach($list as $item)
                {
                    $cateid = isset($item['subject']['cateid']) ? trim($item['subject']['cateid']): 0;

                    $item['cate'] =  $this->CategoryModel->where(['id'=> $cateid])->value('name');
                }
            }

            $data = [
                'count' => $count,
                'list'  => $list
            ];

            if($list)
            {
                //成功返回
                $this->success('返回列表',null,$data);
                exit;
            }else
            {
                //失败返回
                $this->error('暂无数据',null,$data);
                exit;
            }
        }


        return $this->view->fetch();
    }

    //我的关注
   
    public function likes()
    {   
         //判断是否有ajax请求
         if($this->request->isAjax())
     {
         $page = $this->request->param('page',1,'trim');
         $limit = $this->request->param('limit',10,'trim');
         $keywords = $this->request->param('keywords','','trim');

         //偏移量
         $start = ($page-1)*$limit;

         $where = ['busid' => $this->view->AutoLogin['id']];

         //查询数据总条数
         $count = $this 
                        ->LikesModel
                        ->with(['business','teacher'])
                        ->where($where)
                        ->count();

         //查询数据
         $list = $this->LikesModel
                      ->with(['business','teacher'])
                      ->where($where)
                      ->limit($start,$limit)
                      ->select();

         $data = [
             'count' => $count,
             'list'  => $list
         ];

         if($list)
         {
             //成功返回
             $this->success('返回列表',null,$data);
             exit;
         }else
         {
             //失败返回
             $this->error('暂无数据',null,$data);
             exit;
         }
         }

         return $this->view->fetch();
    }

    //消费记录
    public function record()
    {   
        if($this->request->isAjax())
        {   
            $page = $this->request->param('page',1,'trim');
            $limit = $this->request->param('limit',10,'trim');
            $keywords = $this->request->param('keywords','','trim');

            //偏移量
            $start = ($page-1)*$limit;

            $where = ['busid' => $this->view->AutoLogin['id']];

            //搜索栏关键词搜索
            if(!empty($keywords))
            {
                $where['title'] = ['LIKE',"%$keywords%"];
            }

            //查询数据总条数
            $count = $this ->RecordModel
                           ->with(['business'])
                           ->where($where)
                           ->count();

            //查询数据
            $list = $this->RecordModel
                         ->with(['business'])
                         ->where($where)
                         ->limit($start,$limit)
                         ->select();

            $data = [
                'count' => $count,
                'list'  => $list
            ];

            if($list)
            {
                //成功返回
                $this->success('返回列表',null,$data);
                exit;
            }else
            {
                //失败返回
                $this->error('暂无数据',null,$data);
                exit;
            }
        }

        return $this->view->fetch();
    }

    // 充值界面 
    public function pay()
    {
        if($this->request->isPost())
        {
            $money = $this->request->param('money', 1, 'trim');
            $type = $this->request->param('type', 'zfb', 'trim');

            if($money <= 0)
            {
                $this->error(__('充值金额不能小于0'));
                exit;
            }

            //携带一个自定义的参数过去
            $third = ['busid' => $this->view->AutoLogin['id']];

            //开始调用支付(组装参数)
            $data = [
                'name' => '余额充值', //标题
                'third' => $third, //传递的第三方的参数
                'total' => $money, //订单原价充值的价格
                'type' => $type, //支付方式
                'cashier' => 1, //是否需要收银台界面
                'jump' => '/home/business/pay?action=success', //订单支付完成后跳转的界面
                'notice' => '/home/pay/business',  //异步回调地址
            ];
            
            //调用模型中的支付方法
            $result = $this->PayModel->payment($data);

            echo $result;
            exit;
        }

        return $this->view->fetch();
    }
}
